package com.googlecode.animeclassifier;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.googlecode.animeclassifier.attribute.Attribute;
import com.googlecode.animeclassifier.attribute.AttributeFactory;
import com.googlecode.animeclassifier.attribute.Attributes;

public class Anime extends BracketFile {
	Map<Attributes, Attribute> attrs;
	
	public Anime(String arg0) {
		super(arg0);
		
		if(this.brackets.size() < 2)
			throw new RuntimeException("Anime filename should has more than 2 brackets");
		
		attrs = new HashMap<Attributes, Attribute>();
		for(String bracket: this.brackets) {
			for(Attribute attr: AttributeFactory.parse(bracket))
				attrs.put(attr.getType(), attr);
		}
	}

	/**
	 * @return the attrs
	 */
	public Map<Attributes, Attribute> getAttrs() {
		return attrs;
	}
	
	static boolean isVideo(String name) {
		if(
				name.endsWith(".avi") ||
				name.endsWith(".mp4") ||
				name.endsWith(".wmv") ||
				name.endsWith(".mkv") ||
				name.endsWith(".rmvb")
		)
			return true;
		return false;
	}
	
	public boolean isValid(String regex) {
		return true;
	}
	
	/**
	 * Move anime to the target directory which is describe by targetCode string
	 * 
	 * @param targetCode targetCode
	 * @param rootDirectory 
	 * @param fileTranslator
	 * @return
	 */
	public String moveAnime(String targetCode, File rootDirectory, FileTranslatable fileTranslator) {
		File from = this.getFile();
		String decodedPath = decode(targetCode);
		boolean decodeSuccess = (decodedPath != null);
		String parentPath = rootDirectory.getAbsolutePath() + File.separator + decodedPath;
		File dest = new File(parentPath, from.getName());
		String ret = null;
		
		if(!from.getAbsolutePath().equals(dest.getAbsolutePath()) && decodeSuccess) {
			ret = fileTranslator.doit(from, dest);
		} else {
			ret = "";
		}
		
		return ret;
	}
	
	/**
	 * Decoded target code to the system path.
	 * 
	 * isDecodedSuccess will be set as false if this decoded failed. 
	 * @param anime
	 * @param targetCode
	 * @return
	 */
	private String decode(String targetCode) {
		String str = new String(targetCode);
		
		try { 
			str = str.replace("%FILENAME%", this.getFile().getName())
			.replace("%YEAR%", this.getAttrs().get(Attributes.YEAR).getString())
			.replace("%NAME%", this.getAttrs().get(Attributes.NAME).getString())
			.replace("%SEASON%", this.getAttrs().get(Attributes.SEASON).getString())
			.replace("/", File.separator);
		} catch(NullPointerException e) {
			str = null;
		}
		
		return str;
	}
}
